import "./style.css";
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/Addons.js";
import gsap from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
import * as dat from "dat.gui";
// import imageSource from './color.jpg'
// console.log('OrbitControls', OrbitControls)

// console.log('imageSource', imageSource)

gsap.registerPlugin(ScrollTrigger);

// 纹理

// // 简单版
// const loadingManager = new THREE.LoadingManager()

// loadingManager.onStart = () => {
//   console.log('onStart')
// }

// loadingManager.onLoad = () => {
//   console.log('onLoad')
// }

// loadingManager.onProgress = (item, loaded, total) => {
//   console.log(`onProgress ${item} ${loaded} ${total}`)
// }

// loadingManager.onError = () => {
//   console.log('onError')
// }
// const textureLoader = new THREE.TextureLoader(loadingManager)
// // const colorTexture = textureLoader.load(
// //   '/textures/door/color.jpg',
// //   // () => {
// //   //   console.log('load')
// //   // },
// //   // () => {
// //   //   console.log('progress')
// //   // },
// //   // () => {
// //   //   console.log('error')
// //   // }
// // )
// const colorTexture = textureLoader.load('/textures/door/color.jpg')
// const alphaTexture = textureLoader.load('/textures/door/opacity.jpg')
// const heightTexture = textureLoader.load('/textures/door/height.png')
// const normalTexture = textureLoader.load('/textures/door/normal.jpg')
// const ambientOcclusionTexture = textureLoader.load('/textures/door/ambientOcclusion.jpg')
// const metalnessTexture = textureLoader.load('/textures/door/metallic.jpg')
// const roughnessTexture = textureLoader.load('/textures/door/roughness.jpg')

// // 复杂版
// // const image = new Image()
// // // 创建纹理
// // const texture = new THREE.Texture(image)
// // image.onload = () => {
// //   // image.src = '/textures/door/color.jpg'

// //   // 纹理需要更新
// //   texture.needsUpdate = true
// // }

// // image.src = '/textures/door/color.jpg'
// /*
//  * 调试器
// */
const gui = new dat.GUI({
  closed: true,
  width: 300,
});

// const parameters = {
//   color: 0xff0000,
//   spin: () => {
//     gsap.to(mesh.rotation, {
//       z: mesh.rotation.z + 30,
//       duration: .4
//     })
//   }
// }

// gui.addColor(parameters, 'color').onChange(() => {
//   mesh.material.color.set(parameters.color)
// })
// gui.add(parameters, 'spin')

const canvas = document.querySelector(".webgl");
const divDom = document.querySelector(".textBox");
// 鼠标

const cursor = {
  x: 0,
  y: 0,
};

// sizes
const sizes = {
  width: window.innerWidth,
  height: window.innerHeight,
};

canvas.addEventListener("mousemove", (e) => {
  // 鼠标位置
  const { clientX, clientY } = e;
  // 鼠标位置
  const { offsetX, offsetY } = e.target;
  // 鼠标位置
  const { width, height } = e.target;
  cursor.x = clientX / sizes.width - 0.5;
  cursor.y = -(clientY / sizes.height - 0.5);
});

const scene = new THREE.Scene();

// 红色方块
const geometry = new THREE.BoxGeometry(1, 1, 1);

const mesh = new THREE.Mesh(
  geometry,
  new THREE.MeshBasicMaterial({ color: 0x00ff00, wireframe: true })
);

scene.add(mesh);

// console.log('geometry', geometry)
// const vertex1 = new THREE.Vector3(0, 0, 0)
// geometry.vertices.push(vertex1)
// const vertex2 = new THREE.Vector3(0, 1, 0)
// geometry.vertices.push(vertex2)
// const vertex3 = new THREE.Vector3(1, 0, 0)
// geometry.vertices.push(vertex3)

// const geometry = new THREE.BufferGeometry()
// let verticesList = []
// for(let i = 0; i< 50; i++) {
//   for(let j=0; j< 3; j++) {
//     let randomValue = [Math.random() -0.5, Math.random() -0.5, Math.random() -0.5]
//     verticesList.push(...randomValue)
//   }
// }
// console.log('verticesList', verticesList)
// const vertices = new Float32Array(verticesList)
// const vertexAttribute = new THREE.BufferAttribute(vertices, 3);
// geometry.setAttribute('position', vertexAttribute);

// const geometry = new THREE.BufferGeometry()

// const count = 500

// const positionArray = new Float32Array(count * 3 * 3)

// for(let i = 0; i< count *3 * 3; i++) {
//   positionArray[i] = (Math.random() - 0.5) * 3
// }

// const positionAttribute = new THREE.BufferAttribute(positionArray, 3)

// geometry.setAttribute('position', positionAttribute)
// const positionArray = new Float32Array(
//   [
//     0, 0, 0,
//     0, 1, 0,
//     1, 0, 0,
//     // 1, 0, 0,
//     // 0, 0, 1,
//     // 1, 0, 1,
//     // 0, 0, 2
//   ]);

// // 每个面需要几个顶点
// const positionAttribute = new THREE.BufferAttribute(positionArray, 3)
// geometry.setAttribute('position', positionAttribute)

// console.log('attribute', geometry.attributes)
// // 材质
// const meterial = new THREE.MeshBasicMaterial({
//   color: 0xff0000,
//   // color: parameters.color,
//   // wireframe: true,
//   // map: roughnessTexture
// });

// const mesh = new THREE.Mesh(geometry, meterial);
// 添加
// scene.add(mesh);

// // 调试
// gui.add(mesh, 'visible', true).name('visible')
// gui.add(meterial, 'wireframe', false).name('wireframe')
// // gui.add(meterial, 'color').name('meterialColor')
// gui.add(mesh.position, 'y').min(-3).max(3).step(0.01).name('positionY')
// gui.add(mesh.position, 'y', -3, 3 , 0.01)
// 坐标轴
// const axesHelper = new THREE.AxesHelper(5,5,5)

// scene.add(axesHelper)

// 相机
const camera = new THREE.PerspectiveCamera(
  75,
  sizes.width / sizes.height,
  0.01,
  100
);
// 正交相机 左 右 上 下 近点 远点

// const aspectRatio = sizes.width / sizes.height;
// const camera = new THREE.OrthographicCamera(-1 * aspectRatio, 1 * aspectRatio, 1, -1, 0.1, 100);
// console.log('camera', camera)
// camera.position.x = 2;
// camera.position.y = 2;
camera.position.z = 4;

gui.add(camera.position, "z").min(2).max(8).step(1).name("cameraZ");
gui.add(mesh.position, "x").min(-2).max(2).step(1).name("meshX");
gui.add(mesh.position, "z").min(-4).max(2).step(1).name("meshX");
gui.add(mesh.rotation, "y").min(-2).max(2).step(0.01).name("meshRotationY");

camera.lookAt(0, 0, 0);
// console.log('caemera', camera)
scene.add(camera);

// gsap timeline

// 轨道控制器
// const controls = new OrbitControls(camera, canvas);

// controls.enabled = false
// 阻尼
// controls.enableDamping = true;
// controls.target.y = 2
// controls.update()

// // 组
// const group = new THREE.Group()
// scene.add(group)

// const cube1 = new THREE.Mesh(
//   new THREE.BoxGeometry(1,1,1,),
//   new THREE.MeshBasicMaterial({ color: 0xff0000})
// )

// group.add(cube1)

// const cube2 = new THREE.Mesh(
//   new THREE.BoxGeometry(1,1,1,),
//   new THREE.MeshBasicMaterial({ color: 0x00ff00})
// )

// cube2.position.x = -2
// group.add(cube2)

// const cube3 = new THREE.Mesh(
//   new THREE.BoxGeometry(1,1,1,),
//   new THREE.MeshBasicMaterial({ color: 0x0000ff })
// )

// cube3.position.x = 2
// group.add(cube3)

// camera.lookAt(mesh.position)

// 渲染器
const renderer = new THREE.WebGLRenderer({
  canvas,
});

renderer.setSize(sizes.width, sizes.height);
renderer.render(scene, camera);

// 确保在页面加载完成后执行此代码
window.addEventListener("load", function () {
  // 创建一个 Timeline
  const tl = gsap.timeline();

  // 使用 ScrollTrigger 注册动画
  gsap.registerPlugin(ScrollTrigger);

  // 配置 ScrollTrigger
  tl.fromTo(
    camera.position,
    {
      x: 0,
      y: 0,
      z: 4,
    },
    {
      x: 3,
      y: 0,
      z: 2.5,
      ease: "power1.inOut",
      scrollTrigger: {
        trigger: ".div-2", // 替换为实际的触发元素
        start: "top bottom",
        end: "bottom bottom",
        scrub: true,
      }
    }
  );

  // 物体移动
  tl.fromTo(
    mesh.position,
    {
      x: 0,
      y: 0,
      z: 0,
    },
    {
      x: 2.5,
      y: 0,
      z: 0,
      ease: "power1.inOut",
      scrollTrigger: {
        trigger: ".div-2", // 替换为实际的触发元素
        start: "top bottom",
        end: "bottom bottom",
        scrub: true,
      }
    }
  );


  // 
  tl.fromTo(
    camera.position,
    {
      x: 3,
      y: 0,
      z: 2,
    },
    {
      x: 0,
      y: 0,
      z: 4,
      ease: "power1.inOut",
      scrollTrigger: {
        trigger: ".div-3", // 替换为实际的触发元素
        start: "top bottom",
        end: "bottom bottom",
        scrub: true,
      }
    }
  );

  // 物体移动
  tl.fromTo(
    mesh.position,
    {
      x: 2.5,
      y: 0,
      z: 0,
    },
    {
      x: 0,
      y: 0,
      z: 0,
      ease: "power1.inOut",
      scrollTrigger: {
        trigger: ".div-3", // 替换为实际的触发元素
        start: "top bottom",
        end: "bottom bottom",
        scrub: true,
      }
    }
  );

  
  tl.fromTo(
    camera.position,
    {
      x: 0,
      y: 0,
      z: 4,
    },
    {
      x: -3,
      y: 0,
      z: 2,
      ease: "power1.inOut",
      scrollTrigger: {
        trigger: ".div-4", // 替换为实际的触发元素
        start: "top bottom",
        end: "bottom bottom",
        scrub: true,
      }
    }
  );

  // 物体移动
  tl.fromTo(
    mesh.position,
    {
      x: 0,
      y: 0,
      z: 0,
    },
    {
      x: -2.5,
      y: 0,
      z: 0,
      ease: "power1.inOut",
      scrollTrigger: {
        trigger: ".div-4", // 替换为实际的触发元素
        start: "top bottom",
        end: "bottom bottom",
        scrub: true,
      }
    }
  );

  tl.fromTo(
    camera.position,
    {
      x: -3,
      y: 0,
      z: 2,
    },
    {
      x: 0,
      y: 0,
      z: 4,
      ease: "power1.inOut",
      scrollTrigger: {
        trigger: ".div-5", // 替换为实际的触发元素
        start: "top bottom",
        end: "bottom bottom",
        scrub: true,
      }
    }
  );

  // 物体移动
  tl.fromTo(
    mesh.position,
    {
      x: -2.5,
      y: 0,
      z: 0,
    },
    {
      x: 0,
      y: 0,
      z: 0,
      ease: "power1.inOut",
      scrollTrigger: {
        trigger: ".div-5", // 替换为实际的触发元素
        start: "top bottom",
        end: "bottom bottom",
        scrub: true,
      }
    }
  );
});
// 时间
let time = new Date();

// 时间
const clock = new THREE.Clock();

window.addEventListener("resize", () => {
  // 更新 sizes
  sizes.width = window.innerWidth;
  sizes.height = window.innerHeight;
  // 更新相机
  camera.aspect = sizes.width / sizes.height;
  camera.updateProjectionMatrix();
  // 更新渲染器
  renderer.setSize(sizes.width, sizes.height);
  renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});

window.addEventListener("dblclick", () => {
  // 全屏
  const fullscreenElement =
    document.fullscreenElement || document.webkitFullscreenElement;
  if (!fullscreenElement) {
    if (canvas.requestFullscreen) {
      canvas.requestFullscreen();
    } else if (canvas.webkitRequestFullscreen) {
      canvas.webkitRequestFullscreen();
    }
  } else {
    if (document.exitFullscreen) {
      document.exitFullscreen();
    } else if (document.webkitExitFullscreen) {
      document.webkitExitFullscreen();
    }
  }
});

let currentHeight = 0;
let scrollHeight = 0;
// window.addEventListener("scroll", () => {
//   scrollHeight = window.scrollY - currentHeight
//   console.log('scrollHeight', scrollHeight)
//   currentHeight = window.scrollY
//   camera.position.x = Math.sin(scrollHeight * 10000) * 3;
//   // console.log('h', window.scrollY, document.querySelector(".textBox").clientHeight)
//   camera.position.z = 4;
// });

// 动画
const tick = () => {
  // console.log(1111)
  // 时间
  // const currentTime = new Date()

  // const deltaTime = currentTime - time
  // time = currentTime

  // mesh.rotation.y += 0.001 * deltaTime

  // const elapsedTime = clock.getElapsedTime();
  // // console.log('elapsedTime', elapsedTime)
  // // mesh.rotation.y = elapsedTime
  // camera.position.x = Math.sin(cursor.x * 10) * 3
  // camera.position.z = Math.cos(cursor.x * 10) * 3
  // camera.position.y = cursor.y * 5
  // controls.update();
  // camera.lookAt(mesh.position);
  console.log('????')
  camera.lookAt(0, -0.1, 0);
  renderer.render(scene, camera);
  window.requestAnimationFrame(tick);
};

tick();
